<template>
  <div>
    <van-nav-bar fixed>
      <template #left>
        <img :src="imgSrc" alt="" class="logo" />
      </template>
      <template #right>
        <van-icon name="search" size="18" color="#fff" @click="$router.push('/search')" />
      </template>
    </van-nav-bar>
    <van-tabs v-model="channelId" animated sticky offset-top="1.226667rem">
      <van-tab
        v-for="item in channelList"
        :title="item.name"
        :key="item.id"
        :name="item.id"
      >
        <ArticleList :cid="item.id" />
      </van-tab>
    </van-tabs>
    <van-icon
      name="plus"
      size="0.37333334rem"
      class="moreChannels"
      @click="show = true"
    />
    <!-- 弹出层组件 -->
    <van-popup v-model="show" class="edit_wrap" @closed="onPopupClosed">
      <!-- 弹出层的主体区域 -->
      <channel-edit
        ref="channelEdit"
        @changeChannel="changeChannel"
        @removeChannel="removeChannelFn"
        @addChannel="addChannelFn"
        @close="show = false"
        :channelList="channelList"
      ></channel-edit>
    </van-popup>
  </div>
</template>

<script>
import imgPng from '@/assets/toutiao_logo.png'
import { userChannelAPI, updateChannelAPI } from '@/api'
import ArticleList from './ArticleList.vue'
import ChannelEdit from './ChannelEdit.vue'
export default {
  data () {
    return {
      imgSrc: imgPng,
      channelList: [],
      channelId: 0,
      show: false
    }
  },
  methods: {
    onPopupClosed () {
      this.$refs.channelEdit.isEdit = false
    },
    addChannelFn (val) {
      this.channelList.push(val)
      this.updateChannel()
    },
    removeChannelFn (val) {
      const index = this.channelList.findIndex((item) => item.id === val.id)
      // console.log(index)
      this.channelList.splice(index, 1)
      this.updateChannel()
    },
    changeChannel (val) {
      this.channelId = val.id
    },
    async updateChannel () {
      const list = this.channelList.filter((item) => item.id !== 0)
      const resArr = list.map((item, index) => {
        const mewObj = { ...item }
        mewObj.seq = index + 1
        delete mewObj.name
        return mewObj
      })
      await updateChannelAPI({
        channels: resArr
      })
    }
  },
  async created () {
    const res = await userChannelAPI()
    this.channelList = res.data.data.channels
  },
  components: { ArticleList, ChannelEdit }
}
</script>
<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
/deep/ .van-tabs__content {
  padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 999;
}
.edit_wrap {
  width: 100%;
  height: 100%;
}
</style>
